package view.editor;

import java.awt.Point;
import java.util.HashMap;
import java.util.Map;

import main.model.Component;

import com.mxgraph.model.mxCell;
import com.mxgraph.swing.mxGraphComponent;

import controller.editor.EditorController;

public class Layout {

	private Map<mxCell, Component> componentInformation;
	private mxGraphComponent graphComponent;
	private EditorController controller;
	
	public Layout(CanvasView canvas, EditorController controller){
		this.setComponentInformation(new HashMap<mxCell, Component>());
		this.controller = controller;
	}

	public Layout(CanvasView instance) {
		this.setComponentInformation(new HashMap<mxCell, Component>());
		this.controller = instance.getController();
	}

	public mxCell getSelectedCell(Point p){
		Double x = p.getX();
		Double y = p.getY();
		Object cell = this.graphComponent.getCellAt(x.intValue(), y.intValue());
		if (cell != null){
			return (mxCell)cell;
		}
		return null;
	}

	public void setGraphComponent(mxGraphComponent graphComponent) {
		this.graphComponent = graphComponent;
	}
	
	public mxGraphComponent getGraphComponent(){
		return this.graphComponent;
	}

	public void bindComponentPoint(mxCell cell, Component component) {
		this.getComponentInformation().put(cell, component);
		Double x = new Double(cell.getGeometry().getX());
		Double y = new Double(cell.getGeometry().getY());
		Point p = new Point(x.intValue(), y.intValue());
		this.controller.bindComponentToPoint(component, p);
	}

	public void updateComponent(mxCell currentCell) {
		Component component = this.getComponentInformation().get(currentCell);
		if (component != null){
			this.controller.updateLayout(component, currentCell.getGeometry().getPoint());
		}
	}

	public Component getComponent(Point point) {
		mxCell selectedCell = getSelectedCell(point);
		return getComponentInformation().get(selectedCell);
	}
	
	public Component getComponent(mxCell selectedCell){
		return getComponentInformation().get(selectedCell);
	}

	public void cleanLists() {
		this.setComponentInformation(new HashMap<mxCell, Component>());
	}

	public void setComponentInformation(Map<mxCell, Component> componentInformation) {
		this.componentInformation = componentInformation;
	}

	public Map<mxCell, Component> getComponentInformation() {
		return componentInformation;
	}
	
}
